/**
 * 解决 refreshToken 不存在时，刷新token
 * */ 

import axios from 'axios';
import { setToken, setRefreshToken, getToken} from './token';
import { refreshToken, isRefreshRequest } from './refreshToken';

const ins = axios.create({
  baseURL: 'http://localhost:9527',
  headers: {
    Authorization: `Bearer ${getToken()}`
  }
});

ins.interceptors.response.use(async (res) => {
  if (res.headers.authorization) {  // 把服务器传的短期token 给保存下来
    const token = res.headers.authorization.replace('Bearer ', '');
    setToken(token)
    ins.defaults.headers.Authorization = `Bearer ${token}`
  }
  if(res.headers.refreshToken) { // 把服务器传的 长期token 给保存下来
    const refreshToken =  res.headers.authorization.replace('Bearer ', '');
    setRefreshToken(refreshToken)
  }
  if (res.data.code === 401 && !isRefreshRequest(res.config)){  // 无权限 
    // 刷新token
    const isSuccess = await refreshToken();
    if (isSuccess) { // 是否刷新到了token
      // 重新请求
      res.config.headers.Authorization = `Bearer ${getToken()}`;
      const resp = await ins.request(res.config);
      return resp;
    } else {
      // 无权限，退出登录
      console.log('到登录页');
      // 根据业务需求去开发
      // ...
      return res.data
    }
    
  }
  return res.data
})

export default ins;